package com.ncu.greendao;

import android.content.Context;
import android.util.Log;

import java.util.List;

public class UserDaoUtil {
    private static final String TAG = UserDaoUtil.class.getSimpleName();
    private DaoManager mManager;

    public UserDaoUtil(Context context){
        mManager  = DaoManager.getInstance();
        mManager.init(context);
    }
    //1.插入单条的人的数据
    public boolean insertUser(User user){
        boolean flag = false;
        flag = mManager.getDaoSession().getUserDao().insert(user) == -1 ? false : true;
        Log.i(TAG, "insert user :" + flag + "-->" + user.toString());
        return flag;
    }
    //2.插入多条人的数据，在子线程中操作  插入形式List
    public boolean insertMultUser(final List<User> userList) {
        boolean flag = false;
        try {
            mManager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for (User user : userList) {
                        mManager.getDaoSession().insertOrReplace(user);
                    }
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    //3.修改一条数据
    public boolean updateUser(User user){
        boolean flag = false;
        try {
            mManager.getDaoSession().update(user);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }
    //删除单条数据
    public boolean deleteUser(User user){
        boolean flag = false;
        try {
            //按照id删除
            mManager.getDaoSession().delete(user);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }
    //删除所有的数据
    public boolean deleteAll(){
        boolean flag = false;
        try {
            //按照id删除
            mManager.getDaoSession().deleteAll(User.class);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }
    //查询所有的数据
    public List<User> queryAllUser(){
        return mManager.getDaoSession().loadAll(User.class);
    }
    //根据主键id查询数据
    public User queryUserById(long key){
        return mManager.getDaoSession().load(User.class, key);
    }

}
